<template>
  <el-dialog class="add-rent" :visible="isVisible" :title="rentForm.type ? '续租合同' : '添加合同'" @close="onCloseDialog">
    <el-form ref="rentFormRef" :model="rentForm" :rules="rentRules" size="medium">
      <!-- 租赁楼宇 -->
      <el-form-item label="租赁楼宇：" prop="buildingId">
        <el-select v-if="!rentForm.type" v-model="rentForm.buildingId">
          <el-option v-for="item in buildingList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
        <el-input v-else :value="rentForm.buildingName" disabled />
      </el-form-item>
      <!-- 租赁起止日期 -->
      <el-form-item label="租赁起止日期：" required>
        <br>
        <el-row>
          <el-col :span="11">
            <el-form-item prop="startTime">
              <el-date-picker
                v-if="!rentForm.type"
                v-model="rentForm.startTime"
                type="date"
                placeholder="开始日期"
                :picker-options="{disabledDate: disabledStartDate}"
              />
              <el-date-picker
                v-else
                v-model="rentForm.startTime"
                type="date"
                placeholder="开始日期"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" style="text-align: center;">至</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="rentForm.endTime"
                type="date"
                placeholder="结束日期"
                :picker-options="{disabledDate: disabledEndDate}"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 租赁合同 -->
      <el-form-item label="租赁合同：" prop="contractUrl">
        <br>
        <el-upload
          action="#"
          class="upload-business"
          :limit="1"
          :http-request="uploadRequset"
          :before-upload="beforeUpload"
          :file-list="fileList"
          :on-error="onUplodError"
          accept=".pdf, .doc, .docx"
        >
          <el-button icon="el-icon-upload2" size="medium" type="primary" plain>上传文件</el-button>
          <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不得超过5M</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <!-- 底部按钮 -->
    <template #footer>
      <el-button type="primary" size="medium" @click="onSaveRent">确定</el-button>
      <el-button size="medium" @click="onCloseDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getUnrentedBuildingAPI } from '@/api/park/building'
import { uploadAPI } from '@/api/upload'
import { addEnterpriseRentAPI } from '@/api/park/enterprise'

export default {
  name: 'AddRent',
  data() {
    return {
      isVisible: false, // 是否显示弹窗
      buildingList: [], // 可租赁的楼宇列表
      // 合同表单数据
      rentForm: {
        buildingId: '', // 租赁楼宇id
        startTime: '', // 租赁开始时间
        endTime: '', // 租赁结束时间
        contractUrl: '', // 租赁合同文件url
        contractId: '', // 租赁合同文件id
        type: 0, // 租赁类型，添加合同0，续签合同1
        enterpriseId: '' // 企业id
      },
      // 合同校验规则
      rentRules: {
        buildingId: [
          { required: true, message: '请选择楼宇', trigger: 'blur' }
        ],
        startTime: [
          { required: true, message: '租赁开始时间', trigger: 'blur' }
        ],
        endTime: [
          { required: true, message: '租赁结束时间', trigger: 'blur' }
        ],
        contractUrl: [
          { required: true, message: '请上传合同', trigger: 'blur' }
        ]
      },
      // 租赁合同文件列表
      fileList: []
    }
  },
  methods: {
    // 获取可租赁的楼宇列表
    async getBuildingList() {
      this.buildingList = await getUnrentedBuildingAPI()
    },
    // 禁用的租赁开始时间
    disabledStartDate(time) {
      return time.getTime() < Date.now()
    },
    // 禁用的租赁结束时间
    disabledEndDate(time) {
      return time.getTime() < new Date(this.rentForm.startTime).getTime() + 8.64e+7
    },
    // 编写上传文件校验逻辑
    beforeUpload(file) {
      console.log(file)
      // 获取文件后缀名
      const fileNameSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      // 文件白名单
      const whiteList = ['pdf', 'doc', 'docx']

      const allowImgType = whiteList.includes(fileNameSuffix)

      const isLt5M = file.size / 1024 / 1024 < 5

      if (!allowImgType) {
        this.$message.error('上传文件只能是 .pdf/.doc/.docx 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 上传合同文件
    async uploadRequset(data) {
      const file = data.file
      const formData = new FormData()

      formData.append('file', file)
      formData.append('type', 'contract')

      const res = await uploadAPI(formData)
      this.rentForm.contractUrl = res.url
      this.rentForm.contractId = res.id
    },
    // 上传失败
    onUplodError() {
      this.$message.error('上传失败')
    },
    // 保存租赁合同
    onSaveRent() {
      // 校验表单
      this.$refs.rentFormRef.validate(async valid => {
        if (valid) {
          if (this.rentForm.buildingName) {
            delete this.rentForm.buildingName
          }
          await addEnterpriseRentAPI(this.rentForm)
          if (this.rentForm.type) {
            this.$message.success('续租成功')
          } else {
            this.$message.success('新增成功')
          }
          // 关闭弹窗
          this.onCloseDialog()
          // 发送消息给父组件，刷新列表
          this.$emit('update-list')
        }
      })
    },
    // 打开弹窗
    open(enterpriseId, row) {
      this.rentForm.enterpriseId = enterpriseId
      if (row.id) {
        this.rentForm.type = 1
        this.rentForm.buildingId = row.buildingId
        this.rentForm.buildingName = row.buildingName

        // 增加空值校验
        if (row.endTime) {
          // 创建日期副本并加1天
          const endDate = new Date(row.endTime)
          endDate.setDate(endDate.getDate() + 1)

          // 格式化为YYYY-MM-DD格式
          const year = endDate.getFullYear()
          const month = String(endDate.getMonth() + 1).padStart(2, '0')
          const day = String(endDate.getDate()).padStart(2, '0')

          this.rentForm.startTime = `${year}-${month}-${day}`
        } else {
          this.rentForm.startTime = ''
        }
      }

      // 获取楼宇列表并显示弹窗
      this.getBuildingList()
      this.isVisible = true
    },
    // 关闭弹窗
    onCloseDialog() {
      this.isVisible = false
      // 重置表单数据
      this.rentForm = {
        buildingId: '', // 租赁楼宇id
        startTime: '', // 租赁开始时间
        endTime: '', // 租赁结束时间
        contractUrl: '', // 租赁合同文件url
        contractId: '', // 租赁合同文件id
        type: 0, // 租赁类型，添加合同0，续签合同1
        enterpriseId: '' // 企业id
      }
      this.fileList = []
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  width: 500px;
  border-radius: 10px;
  .el-dialog__header {
    border-radius: 10px 10px 0 0;
    .el-dialog__title {
      font-size: 16px;
      color: #303133;
      font-weight: bold;
    }
  }
  .el-dialog__body {
    padding: 20px;
    .el-form {
      padding: 0 50px;
      .el-select, .el-date-editor {
        width: 100%;
      }
    }
  }
  .el-dialog__footer {
    padding-top: 15px;
    padding-bottom: 15px;
    background-color: #eee;
    border-radius: 0 0 10px 10px;
  }
}
</style>
